package com.veepeak.server.api;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.veepeak.server.common.DateUtils;
import com.veepeak.server.common.JSONResult;
import com.veepeak.server.domain.ModelCommand;
import com.veepeak.server.domain.Pids;
import com.veepeak.server.domain.VehicleMake;
import com.veepeak.server.domain.VehicleModel;
import com.veepeak.server.repository.ModelCommandRepository;
import com.veepeak.server.repository.PidsRepository;
import com.veepeak.server.service.VehicleService;
import com.veepeak.server.utils.HttpClientUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.RequestEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

@RestController
@RequestMapping(value = "/spider")
public class SpiderApi {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private VehicleService vehicleService;
    @Autowired
    private PidsRepository pidsRepository;
    @Autowired
    private ModelCommandRepository modelCommandRepository;

    @RequestMapping(value = "/pid")
    public JSONObject pid(){
        try {
            //P0 P1 P2 P3 / C0 C1 C2 C3 / B0 B1 B2 B3 / U0 U1 U2 U3 / 0-7
            String url_prefix = "http://www.obd114.com/obd/";
            String[] pid_prefix = {"P0","P1","P2","P3","C0","C1","C2","C3","B0","B1","B2","B3","U0","U1","U2","U3"};
            for( String pidPrefix : pid_prefix) {
                for (int i = 0; i < 4096; i++) {
                    try {
//                        System.out.println(Integer.toHexString(i).toUpperCase());
                        String index = StringUtils.leftPad(Integer.toHexString(i).toUpperCase(),3,"0");
                        String url = url_prefix+pidPrefix+index;
//                        System.out.println(url);
                        Document doc = Jsoup.connect(url)
                        .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0")
                        .get();

                        System.out.println("********************************************");
                        System.out.println(url);
                        String content = doc.getElementById("mw-content-text").text();
                        System.out.println(content);

                        String pid = content.substring(0,content.indexOf("适用于:")).split(":")[1].trim();
                        System.out.println(content.substring(0,content.indexOf("适用于:")));
                        System.out.println(pid);

                        String applyTo = content.substring(content.indexOf("适用于:"),content.indexOf("系统范畴: ")).split(":")[1].trim();
                        System.out.println(content.substring(content.indexOf("适用于:"),content.indexOf("系统范畴: ")));
                        System.out.println(applyTo);

                        String systemScope = content.substring(content.indexOf("系统范畴: "),content.indexOf("中文定义：")).split(":")[1].trim().replace("\"","");
                        System.out.println(content.substring(content.indexOf("系统范畴: "),content.indexOf("中文定义：")));
                        System.out.println(systemScope);

                        String chineseDefine = content.substring(content.indexOf("中文定义："),content.indexOf("英文定义:")).split("：")[1].trim();
                        System.out.println(content.substring(content.indexOf("中文定义："),content.indexOf("英文定义:")));
                        System.out.println(chineseDefine);

                        String englishDefine = content.substring(content.indexOf("英文定义:"),content.indexOf("背景知识: ")).split(":")[1].trim();
                        System.out.println(content.substring(content.indexOf("英文定义:"),content.indexOf("背景知识: ")));
                        System.out.println(englishDefine);

                        String knowledge = content.substring(content.indexOf("背景知识: ")).split(":")[1].trim();
                        System.out.println(content.substring(content.indexOf("背景知识: ")));
                        System.out.println(knowledge);

                        System.out.println("********************************************");
                        System.out.println();

                        Pids pids = new Pids();
                        pids.setPid(pid);
                        pids.setApplyTo(applyTo);
                        pids.setSystemScope(systemScope);
                        pids.setChineseDefine(chineseDefine);
                        pids.setEnglishDefine(englishDefine);
                        pids.setKnowledge(knowledge);
                        pids.setContent(content);
                        pids.setUpdateTime(DateUtils.getDateTime());
                        pidsRepository.save(pids);
                        Thread.sleep(500);
                    } catch (Exception e) {
                        continue;
                    }
                }
            }

        } catch (Exception e) {

        }
        return JSONResult.toSuccessJson("");
    }

    @GetMapping(value = "/car")
    public JSONObject car() throws Exception{
        String[] makeArray = restTemplate.getForObject("https://www.autoblog.com/api/taxonomy/newmake",String[].class);
        for (String make : makeArray ){
            System.out.println(make);
            VehicleMake vehicleMake = new VehicleMake();
            vehicleMake.setName(make);
            vehicleMake = vehicleService.saveMake(vehicleMake);
            String[] modelArray = restTemplate.getForObject("https://www.autoblog.com/api/taxonomy/combined-models?make="+make,String[].class);
            for(String model : modelArray){
                VehicleModel vehicleModel = new VehicleModel();
                vehicleModel.setName(model);
                vehicleModel.setMake(vehicleMake);
                vehicleService.saveModel(vehicleModel);

            }

            Thread.sleep(300);
        }
        return JSONResult.toSuccessJson(makeArray,"");
    }

    @GetMapping(value = "/mid-tid")
    public JSONObject midTid() throws Exception{
        File file = new File("/Users/mabin/project/OBD/MID-TID.xlsx");
        //System.out.println(file.exists());
        //获取输入流
        InputStream stream = new FileInputStream(file);
        Workbook xssfWorkbook = new XSSFWorkbook(stream);
        Sheet midSheet = xssfWorkbook.getSheetAt(0);
        Sheet tidSheet = xssfWorkbook.getSheetAt(1);

        Map<String,String> midMap = Maps.newHashMap();
        Map<String,String> tidMap = Maps.newHashMap();

        for (int i=0; i<56; i++){
            String mid = midSheet.getRow(i).getCell(0).getStringCellValue();
            String midDesc = midSheet.getRow(i).getCell(2).getStringCellValue();
            midMap.put(mid,midDesc);
        }

        for (int i=0; i<11; i++){
            String tid = tidSheet.getRow(i).getCell(0).getStringCellValue();
            String tidDesc = tidSheet.getRow(i).getCell(2).getStringCellValue();
            tidMap.put(tid,tidDesc);
            System.out.println(tid+" -> "+tidDesc);
        }

        for (String mid : midMap.keySet()){
            for (String tid : tidMap.keySet()){
                ModelCommand model = new ModelCommand();
                model.setCategory(ModelCommand.CATEGORY_MODEL_6);
                model.setCompId(mid);
                model.setTestId(tid);
                model.setDescription(midMap.get(mid)+","+tidMap.get(tid));
                modelCommandRepository.save(model);
            }
        }

        return JSONResult.toSuccessJson("");
    }
}
